from rest_framework import serializers
from .models import UserModel,Permission,PermissionType,UserGroup

class UserSer(serializers.ModelSerializer):
    groups = serializers.SerializerMethodField()

    def get_groups(self,obj):
        # 根据用户找到对应的用户组
        groups = UserGroup.objects.filter(user=obj.id)

        # 得到每个用户组，循环遍历

        user_groups = [{'id':i.id,'name':i.name} for i in groups]

        return user_groups

    permissions = serializers.SerializerMethodField()

    def get_permissions(self,obj):
        groups = UserGroup.objects.filter(user=obj.id)

        user_permissions = groups[0].permission.all()
        print('>>>>>>登达',user_permissions)

        # 得到每个用户组权限，循环遍历

        permissions_list = [{'id': i.id, 'name': i.name} for i in user_permissions]

        return permissions_list


    class Meta:
        model = UserModel
        fields = '__all__'


# 权限名称序列化器
class PermissionSer(serializers.ModelSerializer):
    class Meta:
        model = Permission
        fields = '__all__'


# 权限类型序列化器
class PermissionTypeSer(serializers.ModelSerializer):
    class Meta:
        model = PermissionType
        fields = '__all__'


# 用户组序列化器
class UserGroupSer(serializers.ModelSerializer):
    class Meta:
        model = UserGroup
        fields = '__all__'



